package client;

import java.awt.Cursor;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputAdapter;

/** Classe che gestisce lo scroll della mappa tramite drag del mouse.
 *
 */
class DragMoverListener extends MouseInputAdapter implements ActionListener{
	
	private static final int SPEED = 2;
	private final Cursor dc;
	private final Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
	private final Rectangle rect = new Rectangle();
	private final javax.swing.Timer scroller;
	private final JComponent label;
	private final JViewport vport;
	private Point startPt = new Point();
	private Point move  = new Point();
	
	
	/** Costruttore che serve ad implementare il movimento di scroll del pannello della mappa tramite click del mouse.
	 * @param vport 
	 * @param comp
	 */
	public DragMoverListener(JViewport vport, JComponent comp) {
		this.vport = vport;
		this.label = comp;
		this.dc = label.getCursor();
		this.scroller = new javax.swing.Timer(5, this);
		vport.addMouseMotionListener(this);
		vport.addMouseListener(this);
	}
	
	
	public void actionPerformed(ActionEvent e) {
		Rectangle vr = vport.getViewRect();
		int w = vr.width;
		int h = vr.height;
		Point ptZero = SwingUtilities.convertPoint(vport,0,0,label);
		rect.setRect(ptZero.x-move.x, ptZero.y-move.y, w, h);
		label.scrollRectToVisible(rect);
	}
	
	public void mouseDragged(MouseEvent e) {
		scroller.stop();
		Point pt = e.getPoint();
		move.setLocation(SPEED*(pt.x-startPt.x), SPEED*(pt.y-startPt.y));
		startPt.setLocation(pt);
		scroller.start();
	}
	
	public void mousePressed(MouseEvent e) {
		label.setCursor(hc);
		startPt.setLocation(e.getPoint());
		scroller.stop();
	}
	
	public void mouseReleased(MouseEvent e) {
		label.setCursor(dc);
		scroller.stop();
	}
	
	
}